<template>
  <div>
    <div class="i_bg">
      <div class="content mar_20">
        <img src="@/assets/images/img1.jpg" />
      </div>

      <!-- 购物车列表 -->
      <div class="content mar_20">
        <div v-if="!isHaveCARList">
          <h2 class="none-title">购物车暂时没有商品，去首页看看吧！</h2>
        </div>
        <table
          border="0"
          class="car_tab"
          style="width: 1200px; margin-bottom: 50px"
          cellspacing="0"
          cellpadding="0"
          v-if="isHaveCARList"
        >
          <tr>
            <td class="car_th" width="490">商品名称</td>
            <td class="car_th" width="140">单价</td>
            <td class="car_th" width="150">购买数量</td>
            <td class="car_th" width="130">小计</td>
            <td class="car_th" width="150">操作</td>
          </tr>
          <tr v-for="(item, index) in cartList" :key="index">
            <td>
              <div class="c_s_img">
                <img
                  :src="`http://117.72.153.227/image/${item.fileName}`"
                  width="73"
                  height="73"
                />
              </div>
              {{ item.productName }}
            </td>
            <td align="center">￥{{ item.price }}</td>
            <td align="center">
              <div class="c_num">
                <button
                  @click="updateQuantity(item.productId, item.quantity - 1)"
                  class="car_btn_1"
                >
                  -
                </button>
                <input
                  type="text"
                  v-model.number="item.quantity"
                  class="car_ipt"
                  @blur="validateQuantity(item)"
                  @keypress="onlyNumber"
                />
                <button
                  @click="updateQuantity(item.productId, item.quantity + 1)"
                  class="car_btn_2"
                >
                  +
                </button>
              </div>
            </td>
            <td align="center" style="color: #ff4e00">
              ￥{{ (item.price * item.quantity).toFixed(2) }}
            </td>
            <td align="center">
              <a @click="showDeleteConfirm(item.productId)">删除</a>&nbsp;
              &nbsp;
            </td>
          </tr>
          <tr height="70">
            <td
              colspan="6"
              style="font-family: 'Microsoft YaHei'; border-bottom: 0"
            >
              <button class="r_txt" @click="clearCart">清空购物车</button>
              <span class="fr"
                >商品总价：<b style="font-size: 22px; color: #ff4e00"
                  >￥{{ totalPrice.toFixed(2) }}</b
                ></span
              >
            </td>
          </tr>
          <tr valign="top" height="150">
            <td colspan="6" align="right">
              <a href="#"
                ><img
                  src="@/assets/images/buy1.gif"
                  @click.prevent="toIndex" /></a
              >&nbsp; &nbsp;
              <a href="#" @click.prevent="toBuyCarTwo"
                ><img src="@/assets/images/buy2.gif"
              /></a>
            </td>
          </tr>
        </table>
      </div>

      <!-- 删除确认对话框 -->
      <div v-show="showDeleteDialog" class="black_overlay"></div>
      <div v-show="showDeleteDialog" class="white_content">
        <div class="white_d">
          <div class="notice_t">
            <span
              class="fr"
              style="margin-top: 10px; cursor: pointer"
              @click="cancelDelete"
              ><img src="@/assets/images/close.gif"
            /></span>
          </div>
          <div class="notice_c">
            <table
              border="0"
              align="center"
              style="font-size: 16px"
              cellspacing="0"
              cellpadding="0"
            >
              <tr valign="top">
                <td>您确定要把该商品移除购物车吗？</td>
              </tr>
              <tr height="50" valign="bottom">
                <td>
                  <a href="#" class="b_sure" @click.prevent="confirmDelete"
                    >确定</a
                  >
                  <a href="#" class="b_buy" @click.prevent="cancelDelete"
                    >取消</a
                  >
                </td>
              </tr>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import axios from "axios";

export default {
  name: "BuyCar",
  data() {
    return {
      cartList: [],
      showDeleteDialog: false,
      deletingProductId: null,
      isHaveCARList: false,
    };
  },
  computed: {
    // 计算总价
    totalPrice() {
      return this.cartList.reduce((total, item) => {
        return total + item.price * item.quantity;
      }, 0);
    },
  },
  created() {
    this.loadCartData();
  },
  methods: {
    onlyNumber(event) {
      const keyCode = event.keyCode || event.which;
      if (keyCode < 48 || keyCode > 57) {
        event.preventDefault();
      }
    },
    validateQuantity(item) {
      // 如果输入不是数字或为空，重置为1
      if (isNaN(item.quantity) || item.quantity === "") {
        item.quantity = 1;
        this.$message.warning("请输入有效数量");
        return;
      }
      // 确保是整数
      item.quantity = parseInt(item.quantity);
      // 最小值为1
      if (item.quantity < 1) {
        item.quantity = 1;
        this.$message.warning("数量不能小于1");
      }
      // 调用更新方法
      this.updateQuantity(item.productId, item.quantity);
    },
    // 加载购物车数据
    async loadCartData() {
      try {
        const response = await axios.get(`/api/shoppingCart/getShoppingCart`);
        console.log("购物车回调数据:", response);
        if (response.data.code === 200) {
          if (!response.data.list || response.data.list.length === 0) {
            this.isHaveCARList = false;
            this.cartList = [];
          } else {
            this.cartList = response.data.list;
            this.isHaveCARList = true;
          }
        } else {
          this.$message.error("获取购物车数据失败");
        }
      } catch (error) {
        console.error("加载购物车数据出错:", error);
        this.$message.error("加载购物车数据出错");
      }
    },

    // 更新商品数量
    // 更新商品数量方法修改
    async updateQuantity(productId, newQuantity) {
      if (newQuantity < 1) {
        this.$message.warning("数量不能小于1");
        return;
      }

      try {
        // 构建完整的购物车对象
        const item = this.cartList.find((item) => item.productId === productId);
        if (!item) return;

        const updateData = {
          productId: productId,
          quantity: newQuantity,
          price: item.price,
          productName: item.productName,
          fileName: item.fileName,
        };

        const response = await axios.post(
          `/api/shoppingCart/updateProductInCart`,
          updateData
        );

        if (response.data.code === 200) {
          item.quantity = newQuantity;
          item.cost = item.price * newQuantity;
          this.$message.success("数量更新成功");
          await this.$store.dispatch("fetchCart");
        } else {
          this.$message.error("更新数量失败");
          // 恢复原值
          this.loadCartData();
        }
      } catch (error) {
        console.error("更新数量出错:", error);
        this.$message.error("更新数量出错");
        // 恢复原值
        this.loadCartData();
      }
    },

    // 显示删除确认对话框
    showDeleteConfirm(productId) {
      console.log("删除按钮被点击，productId:", productId);
      this.deletingProductId = productId;
      this.showDeleteDialog = true;
      console.log("showDeleteDialog 值:", this.showDeleteDialog);
    },

    // 确认删除商品
    async confirmDelete() {
      console.log("确认删除，productId:", this.deletingProductId);
      if (!this.deletingProductId) return;

      try {
        const response = await axios.delete(
          `/api/shoppingCart/deleteProductFromCart?productId=${this.deletingProductId}`
        );

        if (response.data.code === 200) {
          this.cartList = this.cartList.filter(
            (item) => item.productId !== this.deletingProductId
          );
          this.$message.success("删除成功");
          await this.$store.dispatch("fetchCart");
          this.loadCartData();
        } else {
          this.$message.error("删除失败");
        }
      } catch (error) {
        console.error("删除商品出错:", error);
        this.$message.error("删除商品出错");
      } finally {
        this.cancelDelete();
      }
    },

    // 取消删除
    cancelDelete() {
      this.showDeleteDialog = false;
      this.deletingProductId = null;
    },

    // 清空购物车
    async clearCart() {
      try {
        const response = await axios.delete(
          `/api/shoppingCart/clearShoppingCart`
        );

        if (response.data.code === 200) {
          this.cartList = [];
          this.$message.success("购物车已清空");
          await this.$store.dispatch("fetchCart");
          this.loadCartData();
        } else {
          this.$message.error("清空购物车失败");
        }
      } catch (error) {
        console.error("清空购物车出错:", error);
        this.$message.error("清空购物车出错");
      }
    },

    toBuyCarTwo() {
      this.$router.push({ name: "BuyCarTwo" });
    },
    toIndex() {
      this.$router.push("/");
    },
  },
};
</script>
<style>
.none-title {
  text-align: center;
}
</style>